/*
 * Copyright 2012 Focus Technology, Co., Ltd. All rights reserved.
 */
package com.coderonrails.cdistr.master.comint;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import com.coderonrails.cdistr.master.session.SlaveInfo;
import com.coderonrails.cdistr.master.session.SlaveManager;

/**
 * ServerThread.java
 * 
 * @author chenjianguo
 */
public class ManageServerThread extends ServerThread {

    /*
     * (non-Javadoc)
     * @see com.coderonrails.cdistr.master.comint.ServerThread#doProcess(java.net.Socket)
     */
    @Override
    public void doProcess(Socket socket) {
        try {
            InputStream is = socket.getInputStream();
            List<Byte> bytesList = new ArrayList<Byte>();
            byte[] buff = new byte[4096];
            int length = 0;
            while ((length = is.read(buff)) > 0) {
                for (int i = 0; i < length; i++) {
                    bytesList.add(buff[i]);
                }
            }

            byte[] bytes = new byte[bytesList.size()];
            for (int i = 0; i < bytesList.size(); i++) {
                bytes[i] = bytesList.get(i);
            }
            String mess = new String(bytes);
            String encode = mess.split("#")[0];
            mess = new String(bytes, encode);

            // 解析消息头
            String[] arr = mess.split("##");
            SlaveInfo slave = new SlaveInfo();
            slave.setSlaveCode(arr[1] + "_" + arr[2]);
            slave.setSlaveHost(arr[1]);
            slave.setSlaveName(arr[3]);
            slave.setLoginTime(System.currentTimeMillis());
            slave.setLastChectTime(System.currentTimeMillis());
            slave.setStatus(1);

            SlaveManager.getInstance().addSlaveInfo(slave);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (socket != null) {
                try {
                    socket.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
